package xdu.lz.protocol.http;

import xdu.lz.framework.RequestWrap;
import xdu.lz.provider.api.HelloService;
import org.apache.commons.io.IOUtils;
import xdu.lz.register.LocalRegister;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class HttpServerHandler {

    /**
     * 处理Http请求
     * @param req
     * @param resp
     */
    public void handler(HttpServletRequest req, HttpServletResponse resp) {

        try {
            //解析是空指针
//            Object object = JSONObject.parseObject(req.getInputStream(), Object.class);
//            RequestWrap invocation = JSONObject.parseObject(req.getInputStream(), RequestWrap.class);
            RequestWrap invocation
                    = new RequestWrap(HelloService.class.getName(),
                    "sayHello",new Class[]{String.class},new String[]{"perdu"});
            String interfaceName = invocation.getInterfaceName();
            //通过接口名，拿到对应的实现类的字节码
            Class implClass = LocalRegister.get(interfaceName);
            //通过Invocation指定的方法名和方法参数，获取方法
            Method method =
                    implClass.getMethod(invocation.getMethodName(), invocation.getParamType());
            //执行方法
            String result = (String) method.invoke(implClass.newInstance(), invocation.getParams());

            System.out.println("tomcat:" + result);
            //返回给客户端httpClient
            IOUtils.write(result, resp.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
